package cn.mdmm.user.service.impl.city;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;

import cn.mdmm.user.entity.city.City;
import cn.mdmm.user.service.city.CityDubboService;
import cn.modoumama.redis.service.RedisService;

/**
 * 城市业务 Dubbo 服务层实现层
 *
 * Created by bysocket on 28/02/2017.
 */
// 注册为 Dubbo 服务
@Service(version = "1.0")
public class CityDubboServiceImpl implements CityDubboService {
	 private static final Logger LOGGER = LoggerFactory.getLogger(CityDubboServiceImpl.class);

	 @Autowired
	 private RedisService redisService;
	 


	@Override
	public Long saveCity(City city) {
		 // 从缓存中获取城市信息
        String key = "city_" + city.getId();
        // 插入缓存
        redisService.set(key, city, 180l);
		return null;
	}
 
 
    /**
     * 获取城市逻辑：
     * 如果缓存存在，从缓存中获取城市信息
     * 如果缓存不存在，从 DB 中获取城市信息，然后插入缓存
     */
    public City findCityById(Long id) {
    	City city = null;
        // 从缓存中获取城市信息
        String key = "city_" + id;

        // 缓存存在
        boolean hasKey = redisService.hasKey(key);
        if (hasKey) {
            city = (City) redisService.get(key);
        }

        return city;
    }

    /**
     * 更新城市逻辑：
     * 如果缓存存在，删除
     * 如果缓存不存在，不操作
     */
    @Override
    public Long updateCity(City city) {
        // 缓存存在，删除缓存
        String key = "city_" + city.getId();
        boolean hasKey = redisService.hasKey(key);
        if (hasKey) {
        	redisService.delete(key);

            LOGGER.info("CityServiceImpl.updateCity() : 从缓存中删除城市 >> " + city.toString());
        }

        return 1l;
    }

    @Override
    public Long deleteCity(Long id) {

        // 缓存存在，删除缓存
        String key = "city_" + id;
        boolean hasKey = redisService.hasKey(key);
        if (hasKey) {
        	redisService.delete(key);

            LOGGER.info("CityServiceImpl.deleteCity() : 从缓存中删除城市 ID >> " + id);
        }
        return 1l;
    }
}
